import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio, Modal, DatePicker
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../../../config/global';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { ProductCategory } from '../_common/productCategory';
import ToastUtil from '../../../../utils/toast';
import { SlideSelect } from '../../../../components/common/slideSelect';
import { months } from 'moment';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../../imgs/sanjiao3.png');
const correct = require('../../../../imgs/global/correct.png');
let selectIcon = require('../../../../imgs/select.png');
let timeIcon = require('../../../../imgs/time.png');
let quanIcon = require('../../../../imgs/qiehuan11.png');
let ziIcon = require('../../../../imgs/qiehuan.png');


const TAB_LIST = [
  {
    name: '采购计划',
    status: 'AUTH_WAIT',
    count: 0,
  },
  {
    name: '销售计划',
    status: 'AUTH_UNPASS',
    count: 0,
  },
]
const TAB_DATA = [
  {
    name: '自营',
    count: 10,
  },
  {
    name: '泉化',
    count: 10,
  },
]

export class PlanApproval extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '经营计划审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props)
    let { tabIndex } = props.navigation.state.params || {};
    this.tabIndex = tabIndex || '0';
    this.state = {
      typeKey: 'purchasePlanApply',  //采销类型
      goodsTreeList: [],
      status: 'data',
      listData: [],
      listDataNum: [],
      refreshIcon: false, // 下拉刷新图标
      alertShow: false,
      tabIndexs: 0,
      isLock: false,
      itemName: '全部三级分类',
      itemNameProuct: '',
      seclet: false,
      modalTime: false,
      modalVisible: false,
      itemNameCheck: [],
      isGoods: Boolean,
      tabIs: '0', // 默认自营
      firstIndex: 0,
      tabInS: 0,
      ChaseQhData: 0,//
      chatnNmber: 0,
      saleNumber: 0,
      saleNbr: 0,
      teamIds: null,
      goodsCateId: null,
      orderType: 'P',
      searching: false,
      countData: [],
      init: true,
      planMonths: {},
      countNums: 0, // 统计值
      goodsCateIds: [],
      isInit: false,
      isOk: false,
    };
    this.pageParams = {  // 参数
      planMonth: null,
      corpId: null,
      corpIdList: [],
      teamIds: null,
      goodsCateIds: null
    }
    this.choiceArr = [];
    this.reload = true; //判断是整个页面刷新还是下拉刷新
  }

  async componentWillMount () {
    this._init();
  }

  _init = async () => {
    await this._initTime();
    await this._initCorpiInit();
    await this._getGoodsClass();
    await this._getGoodsBock();
    await this.initPage();
  }

  //时间初始化
  _initTime = () => {
    const date = new Date;
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).substr(-2);
    const time = year + month; // 默认当前月份传的参数
    const times = year + '-' + month;
    this.pageParams.planMonthTime = times;
    // this.pageParams.planMonth = time;
    const arrAyyDay = [];
    const objOneData = {};
    const objTwoData = {};
    const objthreeData = {};
    const objfoureData = {};
    const objDayData = {};
    const objData = {};
    objOneData['corpName'] = this.GetDateStr(-3); //前三个月
    objTwoData['corpName'] = this.GetDateStr(-2); //前二个月
    objthreeData['corpName'] = this.GetDateStr(-1); //前一个月
    objfoureData['corpName'] = this.GetDateStr(0); //当前月
    objDayData['corpName'] = this.GetDateStr(1); //后一个月
    objData['corpName'] = this.GetDateStr(2)

    arrAyyDay.push(objOneData, objTwoData, objthreeData, objfoureData, objDayData, objData)
    this.pageParams.listTime = arrAyyDay;
    // console.log(this.pageParams.listTime, '这是时间数组')

  }
  // 时间方法
  GetDateStr = (AddDayCount) => {
    var dd = new Date();
    var y = dd.getFullYear();
    let m;
    let month = dd.getMonth() + 1;
    if ((month + AddDayCount) <= 12) {
      if (month + AddDayCount > 0) {
        m = (AddDayCount + month)
        if (m < 10) {
          m = '0' + (AddDayCount + month)
        }
      } else {
        m = (month + AddDayCount + 12);
        y = y - 1
        if (m < 10) {
          m = '0' + (month + AddDayCount - 12)
        }
      }
    } else {
      y = y + 1;
      m = (month + AddDayCount - 12)
      if (m < 10) {
        m = '0' + (month + AddDayCount - 12)
      }
    }
    return y + "-" + m;
  }

  //账套初始化 
  _initCorpiInit = async () => {
    let { firstIndex } = this.state
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    // console.log(userInfo)
    this.choiceArr = userInfo.corpInfoTOs || [];
    let aryyId = [];
    this.choiceArr.forEach((item) => {
      aryyId.push(item.corpId);
    });
    this.pageParams.corpIdList = aryyId;
    this.pageParams.corpId = this.choiceArr[firstIndex].corpId;

  }

  // 产品分类
  _getGoodsClass = async () => {
    let resGoodsList = await HTTP.GET(API_GENERATE(API.GOODS_CATE_GORY_TREE)) // 产品分类
    for (var r = 0; r < resGoodsList.length; r++) {
      resGoodsList[r]['organLeader'] = null
      resGoodsList[r]['isChenckGo'] = false
      resGoodsList[r].goodsList && resGoodsList[r].goodsList.forEach((item, i) => {
        item['isbooks'] = false
      })
    }
    if (resGoodsList) {
      this.setState({
        goodsTreeList: resGoodsList
      })
    }
  }

  //全部产品组
  _getGoodsBock = async () => {
    let resClassify = await HTTP.GET(API_GENERATE(API.TEAM_INFO_TREE)) // 全部产品组
    for (var o = 0; o < resClassify.length; o++) {
      resClassify[o]['organLeader'] = null;
      resClassify[o]['goodsCateName'] = resClassify[o].teamPidName;
      resClassify[o]['isChenckGo'] = false
      for (var k = 0; k < resClassify[o].goodsList.length; k++) {
        resClassify[o].goodsList[k]['goodsName'] = resClassify[o].goodsList[k].teamName;
        resClassify[o].goodsList[k]['isbooks'] = false;
      }
    }
    if (resClassify) {
      this.setState({
        divisionList: resClassify,
      })
    }
  }

  // 初始化数据
  async initPage (refreshIcon) {

    let { firstIndex, goodsCateId, teamIds, planMonths, goodsCateIds, tabIndexs, tabInS, isInit, countNums } = this.state
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload,
      countNums: 0,
      isLock: false,
    })
    this.pageParams.goodsCateIds = goodsCateIds; // 全部分类 id
    this.pageParams.teamIds = teamIds;  // 全部产品组 id
    if (planMonths && planMonths.corpName) {
      planMonths.corpName = planMonths.corpName.split('-').join('')
    }
    this.pageParams.planMonth = planMonths && planMonths.corpName ? planMonths.corpName : this.pageParams.planMonth; // 
    // 列表
    // console.log('1111111111', this.pageParams, firstIndex)
    let res = await HTTP.POST(API_GENERATE(API.PLANAPP_LYLIST), this.pageParams);
    // 账套参数
    // if (res && res.length) {
    //   res.forEach(item => {
    //     this.choiceArr.forEach((items, index) => {
    //       if (items.corpId == item.corpId) {
    //         this.choiceArr[index].count = item.count;
    //       }
    //     })
    //   })
    // }
    // console.log('res---9999', res, this.choiceArr)
    if (res) {
      let chatnNmber = res[firstIndex].purchasePlanApply.ownPlanApply.count || 0;// 采购计划自营数
      let saleNumber = res[firstIndex].salePlanApply.ownPlanApply.count || 0;// 销售计划自营数
      let saleNbr = res[firstIndex].salePlanApply.qhPlanApply.count // 销售计划泉化数
      let purchaseCount = res[firstIndex].purchasePlanApply.count || 0; //采购计划总数
      let saleCount = res[firstIndex].salePlanApply.count || 0; // 销售计划总数
      let chaseCount = res[firstIndex].purchasePlanApply.count || 0;// 计划总数
      let salesCount = res[firstIndex].salePlanApply.count || 0;// 销售总数
      TAB_LIST[0].count = purchaseCount; // 采购计划量
      TAB_LIST[1].count = saleCount; //  销售计划量
      let responsepurChaseData;

      if (isInit == false) {
        if (chaseCount > 0) {// 计划总数
          this.state.orderType = 'P'
          if (chatnNmber > 0) { // 采购计划自营数
            this.state.tabIndexs = 0
            this.state.tabInS = 0
          }
        } else {
          this.state.orderType = 'S'
          if (saleNumber > 0) { // 销售计划自营数
            this.state.tabIndexs = 1;
            this.state.tabInS = 0
          } else {
            if (saleNbr > 0) { // 销售计划泉化数
              this.state.tabIndexs = 1
              this.state.tabInS = 1
            } else {
              this.state.tabInS = 0
              this.state.tabIndexs = 0
            }
          }
        }
      }
      if (this.state.tabIndexs == 0) { // 采购
        if (this.state.tabInS == 0) { // 自营
          responsepurChaseData = res[firstIndex].purchasePlanApply.ownPlanApply.list || [];
        } else { // 泉化
          // responsepurChaseData = res[firstIndex].purchasePlanApply.qhPlanApply.list || [];
        }
      } else { //销售
        if (this.state.tabInS == 0) { // 自营
          responsepurChaseData = res[firstIndex].salePlanApply.ownPlanApply.list || [];
        } else { //泉化
          responsepurChaseData = res[firstIndex].salePlanApply.qhPlanApply.list || [];
        }
      }
      for (var b = 0; b < responsepurChaseData.length; b++) {
        responsepurChaseData[b]['isCheck'] = false;
      }

      this.setState({
        listData: responsepurChaseData,
        listDataNum: res,
        status: responsepurChaseData && responsepurChaseData.length > 0 ? 'data' : 'empty',
        countData: res,
        refreshIcon: false,
        chatnNmber: chatnNmber,// 采购计划自营数
        saleNumber: saleNumber,// 销售计划自营数
        saleNbr: saleNbr,// 销售计划泉化数
        isInit: true,
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  // 刷新页面
  reloadPage () {
    this.reload = false;
    this.initPage();
  }
  // 错误回调
  Refresh = () => {
    this.initPage();
  }

  // 切换
  changeTab (index) {
    if (this.tabIndex === index) return;
    this.tabIndex = index;
    this.setState({
      firstIndex: index,
    }, () => {
      this._initCorpiInit();
      this.initPage();
    })
  }

  //tab View
  _renderTabWrap () {
    const { listDataNum } = this.state;
    return (
      <View>
        {listDataNum && listDataNum.length > 1 ? (
          <View style={styles.tabWrap}>
            {
              listDataNum && listDataNum.map((item, index) => {
                return (
                  <TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
                    <Text style={[styles.tabText, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]} numberOfLines={1}>{item.corpName}</Text>
                    <Text style={[styles.tabText, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.count}</Text>
                  </TouchableOpacity>
                )
              })
            }
          </View>
        ) : <View style={{ flexDirection: 'row', height: 20 * scale, backgroundColor: style.color.themeColor }}></View>
        }

      </View>

    )
  }

  handleChange = date => {
    this.setState({
      startDate: date
    });
  };

  // 审批
  approve = async () => {
    const { itemData, orderType, listData, itemSlect, select, isLock, countNums } = this.state;
    // if (this.requesting) return;
    this.reload = true;
    this.setState({ showRejectModal: false });
    // this.requesting = true;
    let sel = [];// 
    let bukey = {};
    if (itemSlect == true) {
      let arr = []
      listData && listData.forEach((item, i) => {
        if (item.isCheck == true) {
          arr.push(item)
        } else if (item.isCheck == false) {
        }
      })
      arr.forEach((items, i) => {
        let arrAyy = items.approveData.split(';')
        for (var u = 0; u < arrAyy.length; u++) {
          let bukey = {};
          var b = arrAyy[u].indexOf(',');
          var rest = arrAyy[u].substr(0, b);
          var last = arrAyy[u].substr(b + 1, arrAyy[u].length - 1)
          bukey['businessKey'] = rest;
          bukey['taskId'] = last;
          sel.push(bukey)
        }
      })
    } else {
      let arrAyy = itemData.approveData.split(';')
      for (var u = 0; u < arrAyy.length; u++) {
        let bukey = {};
        var b = arrAyy[u].indexOf(',');
        var rest = arrAyy[u].substr(0, b);
        var last = arrAyy[u].substr(b + 1, arrAyy[u].length - 1)
        bukey['businessKey'] = rest;
        bukey['taskId'] = last;
        sel.push(bukey)
      }
    }
    let requestParams = {
      orderType: orderType,
      workFlows: sel,
      remark: this.remark,
      status: this.auditResult == 1 ? 'PASS' : 'REJECT'
    };

    if (requestParams.workFlows && requestParams.workFlows.length < 1) {
      ToastUtil.showSuccess(`请先勾选`)
      return
    }
    // console.log('这是没成功数据', requestParams)
    let text = this.auditResult ? '同意' : '驳回';
    this.setState({ status: 'loading' });
    let res = await HTTP.POST(API_GENERATE(API.PLAN_APPLY_AUDIT), requestParams);
    this.requesting = false;
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.initPage()
        this.setState({
          itemSlect: false,
          isLock: false,
          countNums: 0,
        })
      })
    } else {
      this.setState({
        status: 'data',
        itemSlect: false
      })
    }
  }

  // 三级分类 Product Category
  cancelPress = () => {
    this.setState({
      modalVisible: !this.state.modalVisible,
      isGoods: true,
    }, () => {
      this._getGoodsClass();
    });
  }
  // 对应产品组
  cancelProduct = () => {
    this.setState({
      modalVisible: !this.state.modalVisible,
      isGoods: false
    }, () => {
      this._getGoodsBock();
    });
  }
  // 展示对应时间
  cancelTime = () => {
    this.setState({ alertShow: true }, () => {
    })
  }

  //跳详情
  goSkipPage = (item) => {
    let { orderType, tabInS, } = this.state;
    this.props.navigation.navigate('BusinessPlanPage', {
      itemizeName: tabInS == 0 ? '自营资源' : '泉化资源',
      bizClass: tabInS == 0 ? 'OWN_RES' : 'QPCC_RES',
      goodsCateId: item.goodsCateId,
      orderType: orderType,
      corpId: item.corpId,
      planMonth: item.planMonth,
      goodsCateName: item.goodsCateName,
      PlannedMonth: item.planMonth,
      lineName: item.lineName, // 产品线
      teamName: item.teamName, // 产品组
      organs: item.organs, // 全部部门
      corpName: item.corpName, // 账套名称
    })
  }
  // 选中 某个 或者部分
  checkFrozen = (i, isCheck) => {
    let { listData, } = this.state
    listData[i].isCheck = !isCheck;
    this.setState({
      listData
    })
    let arry = [];
    let isLocks = true;
    listData.forEach((item, i) => {
      if (item.isCheck == false) {
        isLocks = false;
      } else if (item.isCheck == true) {
        arry.push(item)
      }
    })
    this.setState({
      isLock: isLocks,
      countNums: arry ? arry.length : 0,

    })
  }
  // 全选
  checkWhole = (isLock) => {
    let { listData } = this.state;
    let number = listData.length
    this.setState({
      isLock: !isLock,
    })
    listData.forEach((item, i) => {
      item.isCheck = !isLock
    })
    if (isLock == true) {
      number = 0;
    }
    this.setState({
      listData,
      countNums: number
    })
  }

  //列表
  _renderListItem = (data) => {
    let { tabIndexs } = this.state
    let item = data.item;
    const { corpId, teamId, isCheck } = data.item
    return (
      <View style={styles.flexBox} >
        <View style={styles.flexTime}>
          <Text style={styles.itemLightText}>{item.time || '--'}</Text>
        </View>
        <TouchableOpacity activeOpacity={.6} style={styles.itemWrap}
          onPress={() => {
            this.goSkipPage(item)
          }}
        >
          <View style={styles.flexSelect} >
            <TouchableOpacity style={styles.flexRow}
              onPress={() => this.checkFrozen(data.index, isCheck)}
            >
              <View style={styles.lockView}>
                {!teamId && corpId !== '1' ? (
                  <Image style={styles.lockImage} source={correct} />
                ) : null}
                {isCheck ? (
                  <Image style={styles.lockImage} source={correct} />
                ) : null}
              </View>
              <View style={{ alignItems: 'flex-start' }}>
                <Text style={styles.itemLightText}>{item.goodsCateName || '--'}</Text>
              </View>
            </TouchableOpacity>
            <View
              style={styles.flexIcon}>
              <Text style={styles.flexTitle}>明细{item.count || '0'}条</Text>
              <Image source={arrowIcon} style={styles.arrowIcon} />
            </View>
          </View>
          <View style={styles.itemBorder}></View>
          <View style={styles.flexPlan}>
            <View style={styles.planName}>
              <View>
                <Text style={styles.planText}>计划量</Text>
                <Text style={styles.planVaule} >{(item.planQuantity || 0).toFixed(3)} 吨</Text>
              </View>
              <View style={{ marginLeft: 10 * scale }}>
                <Text style={styles.planText} >计划月份</Text>
                <Text style={styles.planVaule}>{item.planMonth ? item.planMonth.substr(0, 4) + "-" + item.planMonth.substr(4) : this.pageParams.planMonthTime}</Text>
              </View>
              <View>
                <Text style={styles.planText} >业务组织</Text>
                <Text style={styles.planVaule}>{item.corpName || '--'}</Text>
              </View>
            </View>
            <View>
              {/* {
                 <Text style={styles.business}>提交部门</Text>
              } */}
              <Text style={styles.business}>提交部门</Text>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={styles.definition}>{item.lineName || '--'} | {item.teamName || '--'}</Text>
              </View>
            </View>
            <View style={styles.itemBorder}></View>
            <View style={styles.itemDayTime}>
              <Text style={[styles.consent, styles.consentColor]} onPress={() => {
                this.auditResult = 1;
                this.remark = '';
                this.setState({
                  showRejectModal: true,
                  itemData: item,
                  itemSlect: false,
                })
                // this.consentCreate(item)
              }}>同意</Text>
              <Text style={styles.itemdown} onPress={() => {
                if (item) {
                  this.auditResult = 0;
                  this.remark = '';
                  this.setState({
                    showRejectModal: true,
                    itemData: item,
                    itemSlect: false,
                  })
                } else {
                  ToastUtil.showWarning('没有数据')
                }
              }}>驳回</Text>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    )
  }
  // 全选
  _renderApprove = () => {
    let { isLock, status, listData, countNums } = this.state;
    return (
      <View>
        {status != 'data' ? (
          <View></View>
        ) : (
            <View style={styles.flexWhole}>
              <TouchableOpacity style={styles.flexRow} onPress={() => this.checkWhole(isLock)}>
                <View style={styles.lockView}>
                  {isLock ? <Image style={styles.lockImage} source={correct} /> : null}
                </View>
                <View style={{ alignItems: 'center' }}>
                  <Text style={styles.itemLightText}>已全选 {countNums}</Text>
                </View>
              </TouchableOpacity>
              <View style={styles.itemDayTime}>
                <Text style={[styles.consent,]} onPress={() => {
                  this.auditResult = 1;
                  this.remark = '';
                  this.setState({
                    showRejectModal: true,
                    listData,
                    itemSlect: true,
                  })
                  // this.consentCreate(item)
                }}>同意</Text>
                <Text style={styles.itemdown} onPress={() => {
                  if (listData) {
                    this.auditResult = 0;
                    this.remark = '';
                    this.setState({
                      showRejectModal: true,
                      listData,
                      itemSlect: true,
                    })
                  } else {
                    ToastUtil.showWarning('没有数据')
                  }
                }}>驳回</Text>
              </View>
            </View>)
        }
      </View>
    )
  }

  // 搜索
  async _getGoodsData (searchKey) {
    let { isGoods } = this.state
    if (isGoods) {
      // 全部分组
      let resGoodsList = await HTTP.GET(API_GENERATE(API.GOODS_CATE_GORY_TREE), { searchKey: searchKey.searchCode });
      if (resGoodsList) {
        for (var q = 0; q < resGoodsList.length; q++) {
          resGoodsList[q]['organLeader'] = null
        }
      }
      this.setState({ searching: false, goodsTreeList: resGoodsList || [] })
    } else {
      let resClassify = await HTTP.GET(API_GENERATE(API.TEAM_INFO_TREE), { searchKey: searchKey.searchCode }) // 全部产品组
      if (resClassify) {
        for (var w = 0; w < resClassify.length; w++) {
          resClassify[w]['organLeader'] = null
          resClassify[w]['goodsCateName'] = resClassify[w].teamPidName;
          for (var e = 0; e < resClassify[w].goodsList.length; e++) {
            resClassify[w].goodsList[e]['goodsName'] = resClassify[w].goodsList[e].teamName;
          }
        }
      }
      this.setState({
        searching: false,
        divisionList: resClassify || [],
      })
    }
  }

  // 确认 添加数据
  _getGoodsCode = (data) => {
    let { isGoods } = this.state;
    let itemNameCheck = [];
    this.pageParams.goodsCateIdList = [];
    // console.log(data, '这是添加的数据')
    if (isGoods) {
      let goodsCateIds = []
      data && data.forEach((item, i) => {
        itemNameCheck.push(item.goodsName);
        goodsCateIds.push(item.goodsId)
      })
      this.setState({ itemNameCheck, goodsCateIds, isOk: true }, () => {
      })
    } else {
      let teamIds = []
      data && data.forEach((item, i) => {
        itemNameCheck.push(item.goodsName);
        teamIds.push(item.teamId)
      })
      this.setState({ itemNameCheck, teamIds, isOk: true }, () => {
      })
    }

  }
  // 筛选时间 
  initTime = (data) => {
    this.setState({ planMonths: data, alertShow: false }, () => {
      this.initPage();
    })
  }

  //采销 切换
  changeTabList = (i) => {
    let { saleListData, orderType, ChaseData, tabIndexs, ChaseQhData, saleQhData, firstIndex, tabInS } = this.state;
    this.reload = true;
    tabIndexs = i;
    if (firstIndex == '0') {
      this.setState({
        tabIndexs: i,
        orderType: i == 0 ? 'P' : 'S',
        tabInS: 0,
      }, () => {
        this.initPage()
      })
    } else {
      this.setState({
        tabIndexs: i,
        orderType: i == 0 ? 'P' : 'S',
        tabInS: 0,
      }, () => {
        this.initPage()
      })
    }
  }
  _onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    }
  }
  // 自营 泉化 切换
  changeqiehuan = (i) => {
    let { saleListData, ChaseData, tabIndexs, ChaseQhData, saleQhData, tabInS, firstIndex } = this.state;
    if (tabIndexs == 0) return;
    this.reload = true;
    tabInS = i;
    if (firstIndex == '0') {
      this.setState({
        tabInS: i,
      }, () => {
        this.initPage()
      })
    } else {
      this.setState({
        tabInS: i,
      }, () => {
        this.initPage()
      })
    }
  }
  render () {
    let { itemNameCheck, chatnNmber, saleNumber, saleNbr, ChaseQhData, firstIndex, tabInS, searching,
      tabIndexs, purchaseCount, isGoods, goodsTreeList, planMonths, status, listData, refreshIcon, alertShow,
      itemName, showRejectModal, goodsCateIds, teamIds, modalVisible, divisionList, tabIs, listTime, itemNameProuct } = this.state;
    if (isGoods) {
      this.itemNames = itemName
    } else {
      this.itemsNamego = itemNameProuct
    }
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
          this._init();
        }} />
        <View style={styles.flexItemize}>
          <TouchableOpacity style={styles.flexReclassify} onPress={() => { this.cancelPress() }} >
            <View >
              <Text style={styles.flexVaule}>{this.itemNames ? this.itemNames.substr(0, 4) + '...' : '全部三级分...'}</Text>
            </View>
            <Image source={selectIcon} style={styles.selectIcon} />
          </TouchableOpacity>
          <TouchableOpacity style={styles.flexProduct} onPress={() => { this.cancelProduct() }}>
            <View >
              <Text style={styles.flexVaule}>{this.itemsNamego ? this.itemsNamego.length > 8 ? this.itemsNamego.substr(0, 8) + '...' : this.itemsNamego : '全部产品组'}</Text>
            </View>
            <Image source={selectIcon} style={styles.selectIcon} />
          </TouchableOpacity>
          <TouchableOpacity onPress={() => { this.cancelTime() }}>
            <View style={styles.flexTimes}>
              <Image source={timeIcon} style={styles.flexTimeIocn} />
              <Text style={styles.flexDate}>
                {planMonths.corpName ? planMonths.corpName.substr(0, 4) + "-" + planMonths.corpName.substr(4) : '全部月份'}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
        {this._renderTabWrap()}
        <View style={styles.resource}>
          {
            TAB_LIST.map((items, i) => {
              return (
                <TouchableOpacity key={i} style={[styles.stateItem, tabIndexs == i ? styles.stateItemActive : null, tabIs == i ? styles.flexWz : null]} onPress={() => { this.changeTabList(i) }}>
                  <Text style={[styles.stateItemText, tabIndexs == i ? styles.stateItemTextActive : null]}>{items.name}</Text>
                  <View style={[
                    tabIndexs == i ? items.count > 0 ?
                      styles.flexTextNull : null : items.count > 0 ? styles.stateItemInfo : null,
                    tabIndexs == i ? styles.stateItemInfoActive : null]}></View>
                </TouchableOpacity>
              )
            })}
          {TAB_DATA.map((items, indexs) => {
            return (
              <TouchableOpacity onPress={() => { this.changeqiehuan(indexs) }} style={tabIndexs == 0 ? styles.flexBoxWei : styles.flexBoxAutarky} key={indexs}>
                {tabIndexs == 0 ? (
                  <Text style={[styles.flexAutarky, tabIs == indexs ? styles.flexI : null, tabInS == indexs ? styles.flexColor : null]}>{tabInS == indexs ? items.name : ''}
                   &nbsp;{tabIs == indexs ? chatnNmber : ''}
                  </Text>
                ) : (
                    <Text style={[styles.flexAutarky, tabIs == indexs ? styles.flexI : null, tabInS == indexs ? styles.flexColor : null]}>{items.name}
                      &nbsp;{tabIs == indexs ? saleNumber : saleNbr}
                    </Text>
                  )
                }
                {tabIndexs == 1 && tabIs == indexs ? (
                  <View>
                    {tabInS == indexs ? (
                      <Image source={ziIcon} style={styles.flexZiIcon} />
                    )
                      : <Image source={quanIcon} style={styles.flexZiIcon} />
                    }
                  </View>
                ) : null
                }
              </TouchableOpacity>
            )
          })
          }
        </View>
        {
          status == 'data' ? (
            <View style={{ flex: 1 }}>
              <FlatList
                data={listData}
                renderItem={this._renderListItem}
                refreshing={refreshIcon}
                onRefresh={() => { this.reloadPage() }}
              />
            </View>
          ) : null
        }
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无数据'} onErrorPress={this._onErrorRefresh} />) : null
        }
        {this._renderApprove()}

        <RefuseModal
          titleText={'审批意见'}
          placeholderText={this.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.remark = text;
            this.approve();
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />

        <Modal animationType={"fade"}
          transparent={true}
          onRequestClose={() => { }}
          visible={modalVisible}>
          <View style={styles.back}>
            <TouchableOpacity activeOpacity={1} style={styles.bg} onPress={() => { this.cancelPress() }}>
            </TouchableOpacity>
            <ProductCategory
              searchPress={(searchCode) => {
                this.setState({
                  searching: true
                }, () => {
                  this._getGoodsData(searchCode)
                })
              }}
              data={isGoods ? goodsTreeList : divisionList}
              searching={searching}
              placeholderText={isGoods ? '请输入三级分类' : '请输入产品组'}
              visible={true}
              rightBtnsList={[{
                btnText: '确认查询',
                btnFun: (val, datas) => {
                  if (isGoods) {
                    let isItem;
                    if (datas) {
                      datas.forEach((item, i) => {
                        if (item.isbooks == true) {
                          isItem = goodsCateIds
                        } else {
                          isItem = [];
                        }
                      })
                    } else {
                      isItem = [];
                    }
                    this.setState({
                      itemName: isItem ? itemNameCheck.length && itemNameCheck.join(',') : '全部三级分类',
                      goodsCateIds: isItem ? isItem : [],
                    })
                  } else {
                    let isItem;
                    if (datas) {
                      datas.forEach((item, i) => {
                        if (item.isbooks == true) {
                          isItem = teamIds
                        } else {
                          isItem = [];
                        }
                      })
                    } else {
                      isItem = [];
                    }
                    this.setState({
                      itemNameProuct: isItem ? itemNameCheck.length && itemNameCheck.join(',') : '全部产品组',
                      teamIds: isItem ? isItem : [],
                    })
                  }
                  this.setState({
                    modalVisible: false,
                  }, () => {

                    this.initPage()
                  }
                  )
                }
              }]}
              confirmData={(data) => this._getGoodsCode(data)}
              secondRight={true}
              optionBox={true}
            // bannerBtnContent={'* 已存在的产品可直接发起认领，新增审批中无需重复新增'}
            />
          </View>
        </Modal>

        <SlideSelect
          alertShow={alertShow}
          options={this.pageParams.listTime}
          titile='请选择时间'
          select={(val) => {
            this.initTime(val)
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} />
      </View >
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
    paddingBottom: 30 * scale
  },
  flexCorpName: {
    // flexDirection: 'row',
    fontSize: 14 * scale,
    paddingBottom: 3 * scale,
    color: style.color.white,
    paddingRight: 5 * scale,
    fontWeight: "500",
  },
  flexBox: {
    marginTop: 8 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  flexTime: {
    marginBottom: 7 * scale,
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  flexSelect: {
    flexDirection: 'row',
    marginBottom: 15 * scale,
    marginTop: 5 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    alignItems: 'center',
  },
  flexRow: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center'
  },
  flexIcon: {
    marginBottom: 1 * scale,
    paddingTop: 2 * scale,
    position: 'absolute',
    top: 0,
    right: 0 * scale,
  },
  flexTitle: {
    position: 'absolute',
    top: 0,
    right: 50 * scale,
    alignItems: 'center',
    fontSize: 12 * scale,
    color: 'red',
  },
  flexPlan: {
    marginBottom: 15 * scale,
    marginTop: 10 * scale,
  },
  planName: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
    position: 'relative',
    paddingLeft: 5 * scale,
    paddingRight: 12 * scale,
    marginBottom: 25 * scale,
  },
  planText: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '300',
    color: '#030303',
    opacity: 0.7,
  },
  planVaule: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '500',
    color: '#030303',
    paddingTop: 8 * scale
  },
  lockView: {
    flexDirection: 'row',
    // justifyContent: 'center',
    alignItems: 'center',
    height: 12 * scale,
    width: 12 * scale,
    borderWidth: 1 * scale,
    borderColor: '#0E7FFD',
    // marginLeft: 14 * scale,
    marginRight: 5 * scale,
  },
  content: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: style.color.themeColor,
    justifyContent: "center",
    paddingLeft: 35 * scale
  },
  traffic: {
    flexDirection: 'row',
    fontSize: 14 * scale,
    paddingBottom: 3 * scale,
    color: style.color.white,
    paddingRight: 5 * scale,
    fontWeight: "500",
  },
  flexItemize: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    position: 'relative',
    backgroundColor: style.color.themeColor,
    paddingLeft: 20 * scale
  },
  flexReclassify: {
    flexDirection: 'row',
    position: 'relative',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10 * scale,
    backgroundColor: '#F4F7FE',
    width: 106 * scale,
    height: 37 * scale,
  },
  flexProduct: {
    flexDirection: 'row',
    position: 'relative',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderRadius: 10 * scale,
    backgroundColor: '#F4F7FE',
    width: 162 * scale,
    height: 37 * scale,
    paddingRight: 10 * scale,
    paddingLeft: 15 * scale,
    marginLeft: 12 * scale
  },
  flexVaule: {
    color: '#999898',
    fontSize: 12 * scale,
  },
  selectIcon: {
    tintColor: '#000',
    width: 9 * scale,
    height: 6 * scale
  },
  flexTimes: {
    width: 51 * scale,
    height: 37 * scale,
    marginLeft: 10 * scale,
    marginTop: 2 * scale,
  },
  flexTimeIocn: {
    flexDirection: 'row',
    width: 16 * scale,
    height: 19 * scale,
    marginLeft: 17 * scale,
    tintColor: '#fff'
  },
  flexDate: {
    width: 51 * scale,
    fontSize: 12 * scale,
    marginTop: 3 * scale,
    color: '#fff'
  },
  resource: {
    flexDirection: 'row',
    // alignItems: 'center',
    // justifyContent: "flex-start",
    marginTop: 10 * scale,
  },
  autarky: {
    flexDirection: 'row',
    justifyContent: "center",
    alignItems: 'center',
    borderRadius: 17 * scale,
    // backgroundColor: '#DCEAFE',
    overflow: 'hidden',
    color: '#0E7FFD',
    fontSize: 11 * scale,
    paddingRight: 15 * scale,
    paddingLeft: 15 * scale,
    marginLeft: 17 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
  },
  flexAutarky: {
    flexDirection: 'row',
    justifyContent: "center",
    alignItems: 'center',
    borderRadius: 17 * scale,
    overflow: 'hidden',
    color: '#000000',
    opacity: 0.7,
    fontSize: 14 * scale,
    paddingLeft: 0 * scale,
    paddingRight: 5 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
  },
  flexQhAutarky: {
    flexDirection: 'row',
    justifyContent: "center",
    alignItems: 'center',
    borderRadius: 17 * scale,
    overflow: 'hidden',
    color: '#000000',
    opacity: 0.7,
    fontSize: 14 * scale,
    paddingLeft: 5 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
  },
  flexColor: {
    color: '#0E7FFD',
    opacity: 1,
  },
  flexI: {
    marginLeft: 30 * scale,
  },
  flexBoxAutarky: {
    flexDirection: 'row',
    justifyContent: "center",
  },
  flexBoxWei: {
    flexDirection: 'row',
    marginLeft: 60 * scale,
  },
  flexZiIcon: {
    width: 30 * scale,
    height: 20 * scale,
    marginTop: 6 * scale,
    // marginLeft: 10 * scale,
    // tintColor: '#F4F7FE',
  },
  autarkyColor: {
    backgroundColor: '#DCEAFE',
    fontWeight: '500',
  },
  autarkyBc: {
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
  },
  business: {
    paddingLeft: 30 * scale,
    fontSize: 12 * scale,
    color: '#000000',
  },
  definition: {
    paddingTop: 5 * scale,
    paddingLeft: 30 * scale,
    justifyContent: "flex-start",
    fontSize: 13 * scale,
    color: '#000000',
    fontWeight: '600',
    paddingBottom: 15 * scale
  },
  flexRemark: {
    fontSize: 12 * scale,
    justifyContent: 'flex-start',
    color: '#0091FF',
    fontWeight: '500',
    paddingBottom: 10 * scale,
    paddingLeft: 10 * scale,
  },
  itemLightText: {
    fontSize: 12 * scale,
    color: '#272727',
    fontWeight: '500',
  },
  filterWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: style.color.themeColor,
    paddingTop: 14 * scale,
    paddingBottom: 14 * scale,
  },
  itemWrap: {
    backgroundColor: '#fff',
    width: '100%',
    borderRadius: 8 * scale,
    paddingTop: 14 * scale,
  },
  searchInput: {
    height: 36 * scale,
    width: 270 * scale,
    paddingLeft: 80 * scale,
    paddingRight: 12 * scale,
    backgroundColor: 'rgba(255, 255, 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 8 * scale,
    color: '#fff',
  },
  flexWhole: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    paddingTop: 20 * scale,
    paddingLeft: 20 * scale,
  },
  searchIcon: {
    width: 20 * scale,
    height: 22 * scale,
    position: 'absolute',
    left: 40 * scale,
    top: 8 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
  itemType: {
    // height: 20 * scale,
    width: 58 * scale,
    flexDirection: 'row',
    alignItems: 'flex-start',
    // justifyContent: 'center',
    // flex: 4,
    // backgroundColor: '#FA9B22',
    borderRadius: 4 * scale,
    marginRight: 10 * scale,
  },

  itemBorder: {
    height: 1 * scale,
    backgroundColor: '#E3E7F0',
    marginBottom: 15 * scale,
  },
  arrowIcon: {
    width: 8 * scale,
    height: 12 * scale,
    position: 'absolute',
    right: 0,
    top: 0 * scale,
    right: 20 * scale,
  },
  itemNames: {
    marginLeft: 5 * scale
  },
  itemAccount: {
    fontSize: 12 * scale,
    color: '#272727',
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row'
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  tabText: {
    color: '#fff',
    textAlign: 'center',
    flexWrap: 'wrap',
    overflow: 'hidden',
  },
  tabCount: {
    marginTop: 4 * scale
  },
  tabItem: {
    flex: 1,
    padding: 16 * scale,
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden'
  },
  tabWrap: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'flex-start',
    paddingLeft: 5 * scale,
    // paddingRight: 56 * scale,
  },

  listItem: {
    backgroundColor: '#fff',
    borderRadius: 4 * scale,
    marginBottom: 22 * scale
  },

  userInfo: {
    paddingLeft: 10 * scale,
    paddingRight: 10 * scale,
    paddingBottom: 6 * scale,
    paddingTop: 8 * scale,
    borderStyle: 'solid',
    borderTopColor: '#E3E7F0',
    borderTopWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
  },
  warningItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 13 * scale
  },
  userName: {
    fontSize: 12 * scale,
    marginBottom: 4 * scale,
    opacity: .8
  },
  tabTextWho: {
    paddingTop: 14 * scale
  },
  flexselectTime: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    width: 375 * scale,
    backgroundColor: '#fff',
    height: 228 * scale,
  },
  flexBoxTime: {
    flexDirection: 'row',
    justifyContent: 'center',
    height: 20 * scale,
    alignItems: 'center',
  },
  back: {
    width: 375 * scale,
    backgroundColor: 'rgba(0, 0, 0, .3)',
    height: GLOBAL.SCREEN_HEIGHT,
    flex: 1,
  },
  bg: {
    width: 375 * scale,
    height: '50%',
  },
  stateItemInfo: {
    width: 6 * scale,
    height: 6 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  flexTextNull: {
    width: 6 * scale,
    height: 6 * scale,
    backgroundColor: '#fff',
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItem: {
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    // marginTop: 15 * scale,
    marginBottom: 15 * scale,
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  stateItemText: {
    paddingRight: 4 * scale,
    paddingLeft: 4 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor,
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: '#fff'
  },
  flexWz: {
    marginLeft: 20 * scale
  },

})